package com.liqw.fastswing.ui.controller;

import com.liqw.fastswing.domain.entity.User;
import com.liqw.fastswing.domain.mapper.UserMapper;
import com.liqw.fastswing.service.UserService;
import com.liqw.fastswing.ui.view.UserView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.swing.*;

/**
 * This this controller takes care of displaying and potentially saving a JournalEntry entity.  The preceding
 * Controller actually gets to set the entity.
 */
@Controller
public class UserController extends JFrame {
    @Autowired
    private UserService userService;

    @Autowired
    private MainController mainController;

    private final UserView view;
    private User model;

    /**
     * This constructor is autowired and automagically gets an instance of JournalEntryRepository to allow it to save
     * records to the persistence mechanism when appropriate.
     *
     */
    public UserController() {
        super("用户信息");

        this.view = new UserView() {
            @Override
            protected void saveButtonClicked() {
                doAction();
            }
        };
        this.setContentPane(view.getRootComponent());
        this.setDefaultCloseOperation(HIDE_ON_CLOSE);
        this.pack();
    }

    private void doAction() {
        if(model.isNew()) {
            model.setName(view.getText());
            userService.save(model);
        }
        this.setVisible(false);
        model = null;
        view.setText("");
        mainController.validate();
    }

    /**
     * Set the entity and manipulate the view appropriately.  If the entity is New, then set the View into Write Mode.  If
     * it isn't new, set it in Write mode.
     *
     * @param model - The JournalEntry object to be displayed and - maybe - edited.
     */
    public void setModel(User model) {
        this.model = model;
        if(model.isNew()) {
            view.setText("");
            view.writeMode();
        } else {
            view.setText(model.getName());
            view.viewMode();
        }
    }
}
